package org.lanqiao.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.lanqiao.util.SqlUtil;

import com.google.gson.Gson;

/**
 * 
 * @author 登录
 *
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String username =request.getParameter("username");
		String password =request.getParameter("password");
		String sql="select * from  user where username=? and password =?";
		
		HashMap<String,String>  jsonResult =new HashMap<String,String>();
		try{
				List<HashMap<String,Object>>   list =SqlUtil.executeQuery(sql, username,password);
				if(list.size()>0){
					//获取回话Session对象，用来存储已经登录的用户名信息
					HttpSession  session  =request.getSession();
					//谨记此Key，可用来判定用户是否登录
					session.setAttribute("loginUserKey", username);
					jsonResult.put("code", "200"); //2oo表示成功
					jsonResult.put("info", "登录成功");
				}else{
					jsonResult.put("code", "404"); //404表示用户没有找到
					jsonResult.put("info", "用户名或者密码错误");
				}
		}catch(Exception ex){
			jsonResult.put("500", "连接数据库异常");
		}
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		Gson gson =new Gson();
		String json=gson.toJson(jsonResult);
		PrintWriter  writer  =response.getWriter();
		writer.print(json);
		writer.close();
		
		
	}

}
